package com.icinfo.cloud.provider.common.utils;

import com.icinfo.cloud.provider.common.enums.BusinessContextKeyEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;

import java.util.EnumMap;
import java.util.Map;

/**
 * 线程上下文工具类
 *
 * @author Junfeng.Chen
 * @date 2023/12/11 13:10
 **/
public class BusinessContextUtil {
    /**
     * 线程上下文存储对象
     */
    private static final ThreadLocal<Map<BusinessContextKeyEnum, Object>> BUSINESS_CONTEXT = new InheritableThreadLocal<>();

    /**
     * 设置上下文参数
     *
     * @param keyEnum   上下文参数key
     * @param value 上下文参数值
     */
    public static void set(BusinessContextKeyEnum keyEnum, Object value) {
        Map<BusinessContextKeyEnum, Object> map = get();
        if (map == null) {
            map = new EnumMap<>(BusinessContextKeyEnum.class);
            BUSINESS_CONTEXT.set(map);
        }
        map.put(keyEnum, value);
    }

    /**
     * 获取上下文参数
     *
     * @param keyEnum 上下文key
     * @return 获取的上下文参数
     */
    public static Object get(BusinessContextKeyEnum keyEnum) {
        Map<BusinessContextKeyEnum, Object> map = get();
        return map == null ? null : map.get(keyEnum);
    }

    /**
     * 根据参数类型获取上下文参数
     *
     * @param keyEnum   上下文key
     * @param clazz 上下文参数类型
     * @param <T>   返回的参数类型
     * @return 若找到的参数不能强制转换成指定的类型 可能会抛出类型转换异常
     */
    public static <T> T get(BusinessContextKeyEnum keyEnum, Class<T> clazz) {
        Map<BusinessContextKeyEnum, Object> map = get();
        return map == null ? null : (T) get(keyEnum);
    }

    /**
     * 获取上下文中所有的参数
     *
     * @return
     */
    private static Map<BusinessContextKeyEnum, Object> get() {
        return BUSINESS_CONTEXT.get();
    }

    /**
     * 移除上下文参数
     */
    public static void remove() {
        BUSINESS_CONTEXT.remove();
    }

    /**
     * 判断文书是否需要确认
     *
     * @param documentInfo 业务文书参数配置对象
     * @return true: 需要确认 false: 不需要确认
     */
    public static boolean documentNeedConfirm(ConfigBusiParamDocumentInfo documentInfo) {
        return YesOrNoEnum.YES.getCode().equals(documentInfo.getIsConfirm())
                //文书为电子送达生成的送达回证且时需要当事人确认
                //若为电子送达生成的送达回证则不需要当事人确认
                && !Boolean.TRUE.equals(get(BusinessContextKeyEnum.SDHZ_ELECTRON_SEND_TYPE, Boolean.class));
    }
}
